<template>
  <div class="statistics-container">
    <!-- 双图表并排布局 -->
    <div class="dual-chart-layout">
      <!-- 第一部分：正确率趋势分析 -->
      <div class="chart-card">
        <div class="filter-section">
          <div class="section-title">正确率趋势分析</div>
          <div class="filter-group">
            <div class="filter-item">
              <label>科目：</label>
              <el-select
                v-model="selectedSubject"
                placeholder="请选择科目"
                style="width: 200px"
              >
                <el-option
                  v-for="subject in subjects"
                  :key="subject.value"
                  :label="subject.label"
                  :value="subject.value"
                />
              </el-select>
            </div>

            <div class="filter-item">
              <label>年份：</label>
              <el-select
                v-model="selectedYear"
                placeholder="请选择年份"
                style="width: 120px"
              >
                <el-option
                  v-for="year in years"
                  :key="year"
                  :label="`${year}年`"
                  :value="year"
                />
              </el-select>
            </div>

            <div class="filter-item">
              <label>月份范围：</label>
              <el-select
                v-model="startMonth"
                placeholder="开始月份"
                style="width: 110px"
              >
                <el-option
                  v-for="month in months"
                  :key="`start-${month.value}`"
                  :label="`${month.value}月`"
                  :value="month.value"
                />
              </el-select>
              <span class="month-separator">至</span>
              <el-select
                v-model="endMonth"
                placeholder="结束月份"
                style="width: 110px"
              >
                <el-option
                  v-for="month in months"
                  :key="`end-${month.value}`"
                  :label="`${month.value}月`"
                  :value="month.value"
                />
              </el-select>
            </div>

            <!-- 确认筛选按钮 -->
            <div class="filter-item">
              <el-button
                type="primary"
                @click="handleConfirmFilter"
                :disabled="!isFilterValid"
              >
                确认筛选
              </el-button>
            </div>
          </div>
        </div>

        <!-- 图表展示区域 -->
        <div class="chart-section">
          <div v-if="loading" class="loading-indicator">
            <el-icon class="is-loading" size="24"><Loading /></el-icon>
            <span>数据加载中...</span>
          </div>
          
          <div v-else-if="chartData.length === 0" class="no-data">
            <el-empty description="暂无数据" :image-size="100">
              <template #description>
                <p style="color: #909399; margin-top: 10px">
                  {{ noDataMessage }}
                </p>
              </template>
            </el-empty>
          </div>
          
          <div ref="chartContainer" v-show="chartData.length > 0" class="chart-container"></div>
        </div>
      </div>

      <!-- 第二部分：知识点掌握多维统计 -->
      <div class="chart-card">
        <div class="filter-section">
          <div class="section-title">知识点掌握多维统计</div>
          <div class="filter-group">
            <div class="filter-item">
              <label>科目：</label>
              <el-select
                v-model="selectedSubjectForKnowledge"
                placeholder="请选择科目"
                style="width: 200px"
              >
                <el-option
                  v-for="subject in subjects"
                  :key="subject.value"
                  :label="subject.label"
                  :value="subject.value"
                />
              </el-select>
            </div>
            <div class="filter-item">
              <label>考试类型：</label>
              <el-select
                v-model="selectedExamType"
                placeholder="请选择考试类型"
                style="width: 200px"
              >
                <el-option
                  v-for="examType in examTypes"
                  :key="examType.value"
                  :label="examType.label"
                  :value="examType.value"
                />
              </el-select>
            </div>

            <!-- 确认筛选按钮 -->
            <div class="filter-item">
              <el-button
                type="primary"
                @click="handleConfirmKnowledgeFilter"
                :disabled="!selectedSubjectForKnowledge || !selectedExamType"
              >
                确认筛选
              </el-button>
            </div>
          </div>
        </div>

        <!-- 图表展示区域 -->
        <div class="chart-section">
          <div v-if="knowledgeLoading" class="loading-indicator">
            <el-icon class="is-loading" size="24"><Loading /></el-icon>
            <span>数据加载中...</span>
          </div>
          
          <div v-else-if="knowledgeData.length === 0" class="no-data">
            <el-empty description="暂无数据" :image-size="100">
              <template #description>
                <p style="color: #909399; margin-top: 10px">
                  {{ knowledgeNoDataMessage }}
                </p>
              </template>
            </el-empty>
          </div>
          
          <div ref="knowledgeChartContainer" v-show="knowledgeData.length > 0" class="chart-container"></div>
        </div>
      </div>
    </div>

    <!-- 第三部分：薄弱知识点Top10 -->
    <div class="chart-card" style="margin-top: 20px;">
      <div class="filter-section">
        <div class="section-title">薄弱知识点Top10</div>
        <div class="filter-group">
          <div class="filter-item">
            <label>科目：</label>
            <el-select
              v-model="selectedSubjectForWeakPoints"
              placeholder="请选择科目"
              style="width: 200px"
            >
              <el-option
                v-for="subject in subjects"
                :key="subject.value"
                :label="subject.label"
                :value="subject.value"
              />
            </el-select>
          </div>

          <!-- 确认筛选按钮 -->
          <div class="filter-item">
            <el-button
              type="primary"
              @click="handleConfirmWeakPointsFilter"
              :disabled="!selectedSubjectForWeakPoints"
            >
              确认筛选
            </el-button>
          </div>
        </div>
      </div>

      <!-- 表格展示区域 -->
      <div class="chart-section">
        <div v-if="weakPointsLoading" class="loading-indicator">
          <el-icon class="is-loading" size="24"><Loading /></el-icon>
          <span>数据加载中...</span>
        </div>
        
        <div v-else-if="weakPointsData.length === 0" class="no-data">
          <el-empty description="暂无数据" :image-size="100">
            <template #description>
              <p style="color: #909399; margin-top: 10px">
                {{ weakPointsNoDataMessage }}
              </p>
            </template>
          </el-empty>
        </div>
        
        <el-table
          v-show="weakPointsData.length > 0"
          :data="weakPointsData"
          style="width: 100%"
          stripe
          border
          v-loading="weakPointsLoading"
          :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
        >
          <el-table-column
            type="index"
            label="排名"
            width="80"
            align="center"
          >
            <template #default="scope">
              <el-tag v-if="scope.$index < 3" :type="rankColors[scope.$index]">
                {{ scope.$index + 1 }}
              </el-tag>
              <span v-else>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="题目内容" min-width="240" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-html="formatQuestionContent(row.content)" class="question-text"></div>
            </template>
          </el-table-column>
          <el-table-column prop="chapterName" label="所属章节" width="200" show-overflow-tooltip />
          <el-table-column prop="knowledgePoints" label="所属知识点" min-width="180" show-overflow-tooltip />
          <el-table-column prop="wrongCount" label="错误次数" width="120" align="center">
            <template #default="{ row }">
              <el-tag type="danger">
                {{ row.wrongCount }} 次
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handlePractice(row)">
                去复习
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';
import { Loading } from '@element-plus/icons-vue';
import { useUserStore } from '../store/user.js';
import { debounce } from 'lodash-es';
import katex from 'katex';
import 'katex/dist/katex.min.css';

export default {
  name: 'StatisticsView',
  
  data() {
    return {
      // 正确率趋势分析筛选数据
      selectedSubject: '高等数学',
      selectedYear: new Date().getFullYear(),
      startMonth: 1,
      endMonth: 12,
      chartData: [],
      chartInstance: null,
      loading: false,
      noDataMessage: '请点击确认筛选按钮',
      
      // 知识点掌握多维统计筛选数据
      selectedSubjectForKnowledge: '高等数学',
      knowledgeData: [],
      knowledgeChartInstance: null,
      knowledgeLoading: false,
      knowledgeNoDataMessage: '请点击确认筛选按钮',
      
      // 薄弱知识点Top10筛选数据
      selectedSubjectForWeakPoints: '高等数学',
      weakPointsData: [],
      weakPointsLoading: false,
      weakPointsNoDataMessage: '请点击确认筛选按钮',
      rankColors: ['danger', 'warning', 'primary'],
      
      // 公共数据
      subjects: [
        { value: '高等数学', label: '高等数学' },
        { value: '线性代数', label: '线性代数' },
        { value: '概率论与数理统计', label: '概率论与数理统计' }
      ],
      years: [2023, 2024, 2025],
      months: Array.from({ length: 12 }, (_, i) => ({ value: i + 1 })),
      resizeObserver: null,
      chartRendered: false,
      knowledgeChartRendered: false,

      // 科目ID映射
      subjectIdMap: {
        '高等数学': 1,
        '线性代数': 2,
        '概率论与数理统计': 3
      },
      // 考试类型数据
      examTypes: [
        { value: '1', label: '数学一' },
        { value: '2', label: '数学二' },
        { value: '3', label: '数学三' }
      ],
      selectedExamType: '1',
    };
  },
  computed: {
    isFilterValid() {
      return this.selectedSubject && this.selectedYear && this.startMonth && this.endMonth;
    }
  },
  mounted() {
    window.addEventListener('resize', this.resizeChart);
    this.initResizeObserver();
    
    // 页面加载时自动获取默认数据
    this.fetchData();
    this.fetchKnowledgeData();
    this.fetchWeakPointsData();
  },
  methods: {
    // 格式化题目内容 - 使用KaTeX处理数学公式
    formatQuestionContent(content) {
      if (!content) return '';
      
      try {
        // 预处理内容
        let processedContent = content
          .replace(/\\n/g, '\n')  // 处理换行符
          .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
          .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
            // 处理块级数学公式 $$...$$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: true,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX block formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$$${formula}$$</span>`;
            }
          })
          .replace(/\$([^$\n]+)\$/g, (match, formula) => {
            // 处理行内数学公式 $...$
            try {
              return katex.renderToString(formula.trim(), {
                displayMode: false,
                throwOnError: false,
                strict: false,
                trust: true
              });
            } catch (error) {
              console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
              return `<span class="katex-error">$${formula}$</span>`;
            }
          })
          .replace(/###DOLLAR###/g, '$');  // 恢复转义的美元符号
        
        // 简单处理换行符为HTML换行
        processedContent = processedContent.replace(/\n/g, '<br>');
        
        return processedContent;
      } catch (error) {
        console.error('formatQuestionContent error:', error);
        return content.replace(/\\n/g, '<br>');
      }
    },
    
    // 初始化尺寸监听器
    initResizeObserver() {
      if ('ResizeObserver' in window) {
        this.resizeObserver = new ResizeObserver(debounce(() => {
          this.resizeChart();
          this.resizeKnowledgeChart();
        }, 100));
        
        if (this.$refs.chartContainer) {
          this.resizeObserver.observe(this.$refs.chartContainer);
        }
        if (this.$refs.knowledgeChartContainer) {
          this.resizeObserver.observe(this.$refs.knowledgeChartContainer);
        }
      }
    },
    
    // 正确率趋势分析相关方法
    async fetchData() {
      this.loading = true;
      this.noDataMessage = '数据加载中...';
      
      try {
        const userStore = useUserStore();
        const userId = userStore.userInfo?.userId;
        
        if (!userId) {
          this.noDataMessage = '用户 ID 未找到';
          this.$message.error('用户 ID 未找到，请重新登录');
          return;
        }

        const params = {
          userId: userId,
          subjectName: this.selectedSubject,
          year: this.selectedYear,
          startMonth: this.startMonth,
          endMonth: this.endMonth
        };

        const response = await axios.get('/api/correct-statistics/trend', { params });
        this.chartData = this.processData(response.data || []);
        
        if (this.chartData.length === 0) {
          this.noDataMessage = '没有找到相关数据';
        }
        
        this.$nextTick(() => {
          setTimeout(() => {
            this.renderChart();
            this.chartRendered = true;
          }, 100);
        });
      } catch (error) {
        console.error('请求失败:', error);
        this.noDataMessage = '数据加载失败';
       
        this.chartData = this.getMockData();
        
        this.$nextTick(() => {
          setTimeout(() => {
            this.renderChart();
            this.chartRendered = true;
          }, 100);
        });
      } finally {
        this.loading = false;
      }
    },

    processData(data) {
      const result = [];
      for (let month = 1; month <= 12; month++) {
        const monthKey = `${this.selectedYear}-${String(month).padStart(2, '0')}`;
        const item = data.find(item => item.analysisMonth === monthKey);
        result.push({
          analysisMonth: monthKey,
          accuracyRate: item?.accuracyRate || 0,
          correctQuestions: item?.correctQuestions || 0,
          totalQuestions: item?.totalQuestions || 0,
          hasData: !!item
        });
      }
      return result;
    },

    renderChart() {
      if (!this.chartData.length) return;
      
      const chartDom = this.$refs.chartContainer;
      if (!chartDom) return;
      
      chartDom.style.height = '400px';
      
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      
      this.chartInstance = echarts.init(chartDom);
      
      const xAxisData = this.chartData.map(item => {
        const [_, month] = item.analysisMonth.split('-');
        return `${parseInt(month)}月`;
      });
      
      const accuracyData = this.chartData.map(item => item.accuracyRate);
      const questionData = this.chartData.map(item => item.totalQuestions);
      const hasData = this.chartData.map(item => item.hasData);
      
      const option = {
        backgroundColor: '#fbfbfb',
        title: {
          text: `${this.selectedSubject} 正确率趋势分析`,
          subtext: `(${this.selectedYear}年 ${this.startMonth}月-${this.endMonth}月)`,
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold', color: '#333' },
          subtextStyle: { fontSize: 12, color: '#666' }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross', crossStyle: { color: '#999' } },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#eee',
          borderWidth: 1,
          padding: 12,
          textStyle: { color: '#333', fontSize: 12 },
          formatter: params => {
            const item = this.chartData[params[0].dataIndex];
            const month = xAxisData[params[0].dataIndex];
            
            if (!item.hasData) {
              return `
                <div style="font-weight: bold; margin-bottom: 5px;">${month}</div>
                <div class="tooltip-item">
                  <span class="tooltip-dot" style="background-color: #909399;"></span>
                  <span>无数据记录</span>
                </div>
              `;
            }
            
            return `
              <div style="font-weight: bold; margin-bottom: 5px;">${month}</div>
              <div class="tooltip-item">
                <span class="tooltip-dot" style="background-color: #409EFF;"></span>
                <span>正确率: <strong>${item.accuracyRate}%</strong></span>
              </div>
              <div class="tooltip-item">
                <span class="tooltip-dot" style="background-color: #67C23A;"></span>
                <span>做题量: <strong>${item.totalQuestions}题</strong></span>
              </div>
              <div class="tooltip-item">
                <span class="tooltip-dot" style="background-color: #E6A23C;"></span>
                <span>正确题数: <strong>${item.correctQuestions}题</strong></span>
              </div>
              <div class="tooltip-item">
                <span class="tooltip-dot" style="background-color: #F56C6C;"></span>
                <span>错误题数: <strong>${item.totalQuestions - item.correctQuestions}题</strong></span>
              </div>
            `;
          }
        },
        legend: {
          data: ['正确率', '做题量'],
          right: '5%',
          top: '5%',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: { fontSize: 12, color: '#666' }
        },
        grid: {
          left: '5%', right: '8%', bottom: '15%', top: '20%', containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisTick: { alignWithLabel: true, show: true, length: 6, lineStyle: { color: '#ddd' } },
          axisLabel: { interval: 0, rotate: 0, fontSize: 12, color: '#666', margin: 10 },
          axisLine: { lineStyle: { color: '#999', width: 1 } }
        },
        yAxis: [
          {
            type: 'value',
            name: '正确率',
            nameLocation: 'end',
            nameGap: 8,
            nameTextStyle: { fontSize: 12, color: '#409EFF' },
            min: 0, max: 100, interval: 20,
            axisLabel: { formatter: '{value}%', fontSize: 12, color: '#666' },
            splitLine: { lineStyle: { type: 'dashed', color: '#eee' } },
            axisLine: { show: true, lineStyle: { color: '#999' } }
          },
          {
            type: 'value',
            name: '做题量',
            nameLocation: 'end',
            nameGap: 8,
            nameTextStyle: { fontSize: 12, color: '#67C23A' },
            min: 0,
            max: this.calculateYMax(this.chartData.map(item => item.totalQuestions)),
            axisLabel: { formatter: '{value}题', fontSize: 12, color: '#666' },
            splitLine: { show: false },
            axisLine: { show: true, lineStyle: { color: '#999' } }
          }
        ],
        series: [
          {
            name: '正确率',
            type: 'line',
            yAxisIndex: 0,
            data: accuracyData,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: { color: '#409EFF', borderColor: '#fff', borderWidth: 2 },
            lineStyle: { width: 2, color: '#409EFF', shadowColor: 'rgba(0, 0, 0, 0.1)', shadowBlur: 8 },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.2)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
              ])
            },
            label: {
              show: true, position: 'top',
              formatter: params => params.data > 0 ? `${params.data}%` : '',
              fontSize: 11, color: '#333',
              backgroundColor: 'rgba(255, 255, 255, 0.8)',
              padding: [2, 4], borderRadius: 3
            }
          },
          {
            name: '做题量',
            type: 'bar',
            yAxisIndex: 1,
            data: questionData,
            barWidth: '50%',
            itemStyle: {
              color: ({ dataIndex }) => hasData[dataIndex] ? '#67C23A' : '#ccc',
              borderRadius: 3,
              shadowColor: 'rgba(0, 0, 0, 0.1)', shadowBlur: 4
            },
            label: {
              show: true, position: 'top',
              formatter: params => params.data > 0 ? `${params.data}题` : '',
              fontSize: 11, color: '#333',
              backgroundColor: 'rgba(255, 255, 255, 0.8)',
              padding: [2, 4], borderRadius: 3
            }
          }
        ],
        dataZoom: [
          { type: 'inside', start: 0, end: 100, zoomLock: false },
          { type: 'slider', show: true, bottom: '8%', start: 0, end: 100, height: 15, handleSize: 15 }
        ]
      };
      
      this.chartInstance.setOption(option);
      
      const tooltipStyle = document.createElement('style');
      tooltipStyle.innerHTML = `
        .tooltip-item { display: flex; align-items: center; margin-bottom: 4px; line-height: 1.5; font-size: 12px; }
        .tooltip-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 5px; }
      `;
      document.head.appendChild(tooltipStyle);
    },
    
    calculateYMax(data) {
      const max = Math.max(...data);
      return max <= 0 ? 10 : Math.ceil(max * 1.2);
    },
    
    resizeChart() {
      if (this.chartInstance && this.chartRendered) {
        this.chartInstance.resize();
      }
    },
    
    getMockData() {
      const mockData = [];
      for (let month = 1; month <= 12; month++) {
        const hasData = Math.random() > 0.2;
        
        if (!hasData) {
          mockData.push({
            analysisMonth: `${this.selectedYear}-${month.toString().padStart(2, '0')}`,
            accuracyRate: 0, correctQuestions: 0, totalQuestions: 0, hasData: false
          });
          continue;
        }
        
        const total = Math.floor(Math.random() * 30) + 10;
        const correct = Math.floor(total * (Math.random() * 0.3 + 0.6));
        
        mockData.push({
          analysisMonth: `${this.selectedYear}-${month.toString().padStart(2, '0')}`,
          accuracyRate: Math.round((correct / total) * 100),
          correctQuestions: correct, totalQuestions: total, hasData: true
        });
      }
      return mockData;
    },
    
    handleFilterChange() {
      if (this.startMonth > this.endMonth) {
        this.startMonth = this.endMonth;
      }
    },
    
    handleConfirmFilter() {
      if (this.startMonth > this.endMonth) {
        this.startMonth = this.endMonth;
      }
      this.fetchData();
    },
    
    // 知识点掌握多维统计相关方法
    async fetchKnowledgeData() {
      this.knowledgeLoading = true;
      this.knowledgeNoDataMessage = '数据加载中...';
      
      try {
        const userStore = useUserStore();
        const userId = userStore.userInfo?.userId;
        
        if (!userId) {
          this.knowledgeNoDataMessage = '用户 ID 未找到';
          this.$message.error('用户 ID 未找到，请重新登录');
          return;
        }
        
        const subjectId = this.subjectIdMap[this.selectedSubjectForKnowledge];
        if (!subjectId) {
          this.knowledgeNoDataMessage = '科目ID未找到';
          this.$message.error('未找到对应的科目ID');
          return;
        }

        const params = {
          userId: userId,
          subjectId: subjectId,
          typeId: this.selectedExamType
        };

        const response = await axios.get('/api/knowledge-statistics/chapter-stats', { params });
        this.knowledgeData = response.data || [];
        
        if (this.knowledgeData.length === 0) {
          this.knowledgeNoDataMessage = '没有找到相关数据';
        }
        
        this.$nextTick(() => {
          setTimeout(() => {
            this.renderKnowledgeChart();
            this.knowledgeChartRendered = true;
          }, 100);
        });
      } catch (error) {
        console.error('请求失败:', error);
        this.knowledgeNoDataMessage = '数据加载失败';
        
        this.knowledgeData = this.getMockKnowledgeData();
        
        this.$nextTick(() => {
          setTimeout(() => {
            this.renderKnowledgeChart();
            this.knowledgeChartRendered = true;
          }, 100);
        });
      } finally {
        this.knowledgeLoading = false;
      }
    },
    
    getMockKnowledgeData() {
      const mockData = [];
      const chapters = [
        '函数与极限', '导数与微分', '微分中值定理',
        '不定积分', '定积分', '多元函数微分学',
        '重积分', '曲线积分与曲面积分', '无穷级数', '微分方程'
      ];
      
      chapters.forEach(chapter => {
        const totalQuestions = Math.floor(Math.random() * 50) + 20;
        const correctQuestions = Math.floor(totalQuestions * (Math.random() * 0.3 + 0.5));
        const correctRate = Math.round((correctQuestions / totalQuestions) * 100);
        const progressRate = Math.round((totalQuestions / (totalQuestions + Math.floor(Math.random() * 30))) * 100);
        
        mockData.push({
          chapterName: chapter,
          correctRate: correctRate,
          progressRate: progressRate,
          correctQuestionCount: correctQuestions,
          totalQuestionCount: totalQuestions,
          chapterTotalQuestionCount: totalQuestions + Math.floor(Math.random() * 30)
        });
      });
      return mockData;
    },
    
    renderKnowledgeChart() {
      if (!this.knowledgeData.length) return;
      
      const chartDom = this.$refs.knowledgeChartContainer;
      if (!chartDom) return;
      
      chartDom.style.height = '400px';
      
      if (this.knowledgeChartInstance) {
        this.knowledgeChartInstance.dispose();
      }
      
      this.knowledgeChartInstance = echarts.init(chartDom);
      
      const chapterNames = this.knowledgeData.map(item => item.chapterName);
      const correctRates = this.knowledgeData.map(item => item.correctRate);
      const progressRates = this.knowledgeData.map(item => item.progressRate);
      
      const option = {
        backgroundColor: '#fbfbfb',
        title: {
          text: `${this.selectedSubjectForKnowledge} 章节掌握情况 (${this.getExamTypeName(this.selectedExamType)})`,
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold', color: '#333' }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#eee',
          borderWidth: 1,
          padding: 10,
          formatter: params => {
            const data = this.knowledgeData[params[0].dataIndex];
            return `
              <div style="font-weight: bold; margin-bottom: 6px; font-size: 13px;">${params[0].name}</div>
              <div style="display: flex; flex-direction: column; gap: 3px; font-size: 12px;">
                <div>
                  <span style="display: inline-block; width: 80px;">正确率:</span>
                  <strong>${data.correctRate}%</strong>
                  (做对${data.correctQuestionCount}题 / 共做${data.totalQuestionCount}题)
                </div>
                <div>
                  <span style="display: inline-block; width: 80px;">进度:</span>
                  <strong>${data.progressRate}%</strong>
                  (已做${data.totalQuestionCount}题 / 章节共${data.chapterTotalQuestionCount}题)
                </div>
              </div>
            `;
          }
        },
        legend: {
          data: ['正确率', '进度'],
          right: '5%',
          top: '5%',
          textStyle: { fontSize: 12, color: '#666' },
          itemWidth: 10, itemHeight: 10
        },
        grid: {
          left: '10%', right: '5%', bottom: '15%', top: '20%', containLabel: true
        },
        xAxis: {
          type: 'category',
          data: chapterNames,
          axisLabel: { interval: 0, rotate: 30, fontSize: 12, color: '#666' },
          axisTick: { alignWithLabel: true }
        },
        yAxis: {
          type: 'value',
          name: '百分比',
          nameTextStyle: { fontSize: 12, padding: [0, 0, 0, 30] },
          min: 0, max: 100,
          axisLabel: { formatter: '{value}%', fontSize: 12, color: '#666' },
          splitLine: { lineStyle: { type: 'dashed', color: '#eee' } }
        },
        series: [
          {
            name: '正确率',
            type: 'bar',
            barWidth: '25%',
            data: correctRates,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            label: {
              show: true, position: 'top',
              formatter: '{c}%',
              fontSize: 11, color: '#333'
            }
          },
          {
            name: '进度',
            type: 'bar',
            barWidth: '25%',
            data: progressRates,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#c23531' },
                { offset: 0.5, color: '#d48265' },
                { offset: 1, color: '#d48265' }
              ])
            },
            label: {
              show: true, position: 'top',
              formatter: '{c}%',
              fontSize: 11, color: '#333'
            }
          }
        ]
      };
      
      this.knowledgeChartInstance.setOption(option);
    },
    
    getExamTypeName(examTypeId) {
      return this.examTypes.find(type => type.value === examTypeId)?.label || '未知考试类型';
    },
    
    resizeKnowledgeChart() {
      if (this.knowledgeChartInstance && this.knowledgeChartRendered) {
        this.knowledgeChartInstance.resize();
      }
    },
    
    handleConfirmKnowledgeFilter() {
      this.fetchKnowledgeData();
    },
    
    // 薄弱知识点Top15相关方法
    async fetchWeakPointsData() {
      this.weakPointsLoading = true;
      this.weakPointsNoDataMessage = '数据加载中...';
      
      try {
        const userStore = useUserStore();
        const userId = userStore.userInfo?.userId;
        
        if (!userId) {
          this.weakPointsNoDataMessage = '用户 ID 未找到';
          this.$message.error('用户 ID 未找到，请重新登录');
          return;
        }
        
        const subjectId = this.subjectIdMap[this.selectedSubjectForWeakPoints];
        if (!subjectId) {
          this.weakPointsNoDataMessage = '科目ID未找到';
          this.$message.error('未找到对应的科目ID');
          return;
        }

        const params = {
          userId: userId,
          subjectId: subjectId,
          typeId: this.selectedExamType
        };

        const response = await axios.get('/api/weak-statistics/ranking', { params });
        this.weakPointsData = response.data || [];
        
        if (this.weakPointsData.length === 0) {
          this.weakPointsNoDataMessage = '没有找到相关数据';
        }
      } catch (error) {
        console.error('请求薄弱知识点数据失败:', error);
        this.weakPointsNoDataMessage = '数据加载失败';
        this.$message.error(`加载失败: ${error.message}`);
        this.weakPointsData = this.getMockWeakPointsData();
      } finally {
        this.weakPointsLoading = false;
      }
    },
    
    getMockWeakPointsData() {
      const mockData = [];
      const chapters = ['函数与极限', '导数与微分', '微分中值定理', '不定积分', '定积分', '多元函数微分学'];
      const knowledgePoints = ['函数概念', '极限计算', '导数定义', '微分应用', '积分技巧', '偏导数'];
      
      for (let i = 0; i < 15; i++) {
        const chapterIndex = Math.floor(Math.random() * chapters.length);
        const knowledgeIndex = Math.floor(Math.random() * knowledgePoints.length);
        
        mockData.push({
          questionId: 1000 + i,
          subjectName: this.selectedSubjectForWeakPoints,
          content: `题目内容 ${i + 1}：${chapters[chapterIndex]}相关知识点题目描述，这是一个用于测试的长题目内容，包含了一些示例文本用于展示截取效果。`,
          wrongCount: Math.floor(Math.random() * 10) + 5,
          chapterName: chapters[chapterIndex],
          knowledgePoints: knowledgePoints[knowledgeIndex],
          typeId: this.selectedExamType
        });
      }
      
      return mockData.sort((a, b) => b.wrongCount - a.wrongCount);
    },
    
    handleConfirmWeakPointsFilter() {
      this.fetchWeakPointsData();
    },
    
    handlePractice(row) {
      const subjectId = this.subjectIdMap[row.subjectName];
      
      if (subjectId) {
        this.$router.push({
          path: '/favorites/wrong-questions',
          query: { subject: subjectId, typeId: row.typeId || this.selectedExamType }
        });
      } else {
        this.$message.error('无法找到对应科目信息');
      }
    },
  },
  beforeUnmount() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    
    if (this.knowledgeChartInstance) {
      this.knowledgeChartInstance.dispose();
    }
    
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    
    window.removeEventListener('resize', this.resizeChart);
  }
};
</script>

<style scoped>
.detail-link {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #409EFF;
  text-decoration: none;
  transition: color 0.2s;
}

.detail-link:hover {
  color: #1a56db;
  text-decoration: underline;
}

.statistics-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.dual-chart-layout {
  display: flex;
  gap: 20px;
  width: 100%;
  flex-wrap: wrap;
}

@media (max-width: 1200px) {
  .dual-chart-layout {
    flex-direction: column;
  }
}

.chart-card {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  flex: 1;
  min-width: 0;
  transition: transform 0.3s, box-shadow 0.3s;
}

.chart-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.filter-section {
  padding: 16px;
  border-bottom: 1px solid #f0f2f5;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  margin-right: 6px;
  font-weight: 500;
  color: #606266;
  min-width: 60px;
  font-size: 13px;
  white-space: nowrap;
}

.month-separator {
  margin: 0 6px;
  color: #909399;
  font-size: 13px;
}

.chart-section {
  padding: 16px;
  position: relative;
  min-height: 400px;
}

.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  font-size: 13px;
  z-index: 10;
}

.loading-indicator .el-icon {
  margin-bottom: 8px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

.chart-container {
  width: 100%;
  height: 100%;
}

.question-text {
  line-height: 1.5;
}

/* KaTeX样式优化 */
:deep(.katex) {
  font-size: 1.1em;
  line-height: 1.5;
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  margin: 0.5em 0;
  text-align: center;
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.2em 0;
}

:deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}

@media (max-width: 768px) {
  .filter-group {
    flex-direction: column;
  }
  
  .el-select {
    width: 100% !important;
  }
  
  .chart-section {
    padding: 12px;
    min-height: 350px;
  }
  
  .chart-container {
    height: 350px;
  }
  
  .filter-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
    width: 100%;
  }
  
  .month-separator {
    margin: 6px 0;
    display: block;
    text-align: center;
    width: 100%;
  }
  
  .filter-item.el-button {
    margin-left: 0;
    width: 100%;
  }
}
</style>